import {useEffect, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import FullScreen from "@/layout/FullScreen";
import {IRouteConfig} from "@/routers/routes";
import {LayoutEnum} from "@/enums/LayoutEnum";
import Iframe from "@/layout/Iframe";
import LayoutComponent from "@/layout/LayoutComponent";
import Home from "@/views/Home";
import User from "@/views/System/User";
import {getToken} from "@/utils/auth";

const ComponentData = {
    Home,
    User
}
export const UseGuards = ({route}: { route: IRouteConfig }) => {
    const navigate = useNavigate();
    const [token] = useState(getToken())
    useEffect(() => {
        if (token) {
            if (route.path === '/login') {
                navigate('/')
                return;
            }
        } else {
            if (route.needAuth) {
                navigate('/login')
                return
            }
        }
        document.title = route.title ? `${route.title}-${process.env.REACT_APP_BASE_TITLE}` : process.env.BASE_TITLE
    }, [navigate, route, token]);
    switch (route.pageType) {
        case LayoutEnum.FULLSCREEN:
            return <FullScreen component={route.component}/>
        case LayoutEnum.LAYOUT:
            return <LayoutComponent component={ComponentData[route.name]}/>
        case LayoutEnum.IFRAME:
            return <Iframe url={route.path as string}></Iframe>
        default:
            return <FullScreen component={route.component}/>
    }
};

